package bfsalgorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 733、图像渲染
 */
public class Exercise1 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};

    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        // bfs宽搜
        if(image[sr][sc] == color) {
            return image;
        }
        int prev = image[sr][sc];
        int m = image.length,n = image[0].length;

        Queue<int[]> heap = new LinkedList<>();
        heap.add(new int[]{sr,sc});
        image[sr][sc] = color;

        while(!heap.isEmpty()) {
            int[] t = heap.poll();
            int i = t[0],j = t[1];
            for(int k = 0;k < 4;k++) {
                int x = i + dx[k];
                int y = j + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && image[x][y] == prev) {
                    heap.add(new int[]{x,y});
                    image[x][y] = color;
                }
            }
        }

        return image;
    }
}
